package com.LeetCode.List;

import org.junit.Test;

/**
 * k 个一组反转链表
 */
public class ReverseKNode {

    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0), prev = dummy, curr = head, next;
        dummy.next = head;
        int len = 0;
        while(head!=null){
            len++;
            head = head.next;
        }

        for(int i=0; i<len / k; i++){
            for(int j=0; j<k-1; j++){
                next = curr.next;
                curr.next = next.next;
                next.next = prev.next;
                prev.next = next;
            }
            prev = curr;
            curr = curr.next;
        }
        return dummy.next;
    }

    private ListNode ReverseList(ListNode head, ListNode tail,ListNode prev){
        ListNode pNode = head;
        while(pNode!=tail){
            ListNode next = pNode.next;
            pNode.next = prev;
            prev = pNode;
            pNode = next;
        }
        return tail;
    }

    @Test
    public void test(){
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
//        System.out.println(ReverseList(node1,node3,dummy).next.val);
        ListNode.printList(reverseKGroup(node1,2));
    }
}
